package com.serializer;

import com.google.gson.*;
import com.message.RpcReqMessage;
import com.service.HelloService;

import java.lang.reflect.Type;

/**
 * @author 罗俊华
 * @date 2021/9/1 - 5:33 下午
 */
public class GsonSerializer implements JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> {
    @Override
    public Class<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        String classNameStr = json.getAsString();

        try {
            return Class.forName(classNameStr);
        } catch (ClassNotFoundException e) {

            throw new JsonParseException(e);
        }
    }

    @Override
    public JsonElement serialize(Class<?> src, Type typeOfSrc, JsonSerializationContext context) {

        String name = src.getName();

        return new JsonPrimitive(name);
    }


    /**
     * 当Gson 中有不支持的属性类型时，可以使用这种方法将其json化和反json化
     * @param args
     */
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Class.class, new GsonSerializer()).create();

        RpcReqMessage rpcReqMessage = new RpcReqMessage(1,HelloService.class,null,null,null);

        String json = gson.toJson(rpcReqMessage);

        System.out.println(json);

        RpcReqMessage fromJson = gson.fromJson(json, RpcReqMessage.class);

        System.out.println(fromJson);
    }
}
